import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import Head from 'next/head';
import classNames from 'classnames';
import { Play, Download } from 'lucide-react';
import slideData from './code.js';
import Fragment from './Fragment';

import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import { Navigation } from 'swiper/modules';
import { motion } from 'framer-motion';

import { conversation } from '@/api/ai';

@withRouter
class Comp extends Component {
  wheelTimeout = null; // 节流计时器
  containerRef = React.createRef();
  swiperRef = React.createRef();
  slideshowContainerRef = React.createRef();
  state = {
    title: '项目汇报',
    slides: slideData,
    isPlaying: false,
    activeSlideIndex: 0,
    showFragment: false,
    list:[],
  };

  async componentDidMount() {
    var selectedChat = window.localStorage.getItem('selectedChat')
    await this.getChatDetail(selectedChat)
    
    setTimeout(()=>{
      this.setWidth();
      window.addEventListener('resize', this.setWidth);
      window.addEventListener('keydown', this.handleKeyDown);
      document.addEventListener('fullscreenchange', this.handleFullscreenChange);
      document.addEventListener(
        'webkitfullscreenchange',
        this.handleFullscreenChange,
      );
      document.addEventListener(
        'mozfullscreenchange',
        this.handleFullscreenChange,
      );
      document.addEventListener(
        'MSFullscreenChange',
        this.handleFullscreenChange,
      );
  
      window.removeEventListener('wheel', this.handleWheel, { capture: true });
    },300)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setWidth);
    window.removeEventListener('keydown', this.handleKeyDown);
    document.removeEventListener(
      'fullscreenchange',
      this.handleFullscreenChange,
    );
    document.removeEventListener(
      'webkitfullscreenchange',
      this.handleFullscreenChange,
    );
    document.removeEventListener(
      'mozfullscreenchange',
      this.handleFullscreenChange,
    );
    document.removeEventListener(
      'MSFullscreenChange',
      this.handleFullscreenChange,
    );
    // 确保退出播放时移除事件监听
    window.removeEventListener('wheel', this.handleWheel, { capture: true });
  }

  startSlideshow = () => {
    this.setState({ isPlaying: true }, () => {
      // Request fullscreen for the slideshow container
      setTimeout(() => {
        if (this.slideshowContainerRef.current) {
          const elem = this.slideshowContainerRef.current;
          if (elem.requestFullscreen) {
            elem.requestFullscreen();
          } else if (elem.webkitRequestFullscreen) {
            /* Safari */
            elem.webkitRequestFullscreen();
          } else if (elem.msRequestFullscreen) {
            /* IE11 */
            elem.msRequestFullscreen();
          }

          // 聚焦容器，启用轮播监听
          setTimeout(() => {
            elem.focus();
            this.setState({ showFragment: true });
          }, 400);
        }
      }, 100);
    });
  };

  handleDownload = () => {
    console.log('Download requested');
  };

  setWidth = () => {
    const container = this.containerRef.current;
    if (!container) return;
    // 计算宽度
    this.setState({ containerWidth: container.offsetWidth });
  };

  handleKeyDown = (e) => {
    if (!this.swiperRef.current) return;
    const swiper = this.swiperRef.current.swiper;

    // 左箭头
    if (e.key === 'ArrowLeft') {
      swiper.slidePrev();
    }
    // 右箭头
    else if (e.key === 'ArrowRight') {
      swiper.slideNext();
    }
    // 上箭头
    else if (e.key === 'ArrowUp') {
      swiper.slidePrev();
    }
    // 下箭头
    else if (e.key === 'ArrowDown') {
      swiper.slideNext();
    }
    // ESC键退出全屏和播放模式
    else if (e.key === 'Escape' && this.state.isPlaying) {
      this.setState({ isPlaying: false });
    }
  };

  handleFullscreenChange = () => {
    // 检查是否退出了全屏模式
    if (
      !document.fullscreenElement &&
      !document.webkitFullscreenElement &&
      !document.mozFullScreenElement &&
      !document.msFullscreenElement
    ) {
      // 如果退出全屏，则恢复到之前的状态
      if (this.state.isPlaying) {
        this.setState({
          isPlaying: false,
          activeSlideIndex: 0,
          showFragment: false,
        });
      }
    }
  };

  handleWheel = (e) => {
    if (this.wheelTimeout) return; // 节流中，忽略事件

    // ✅ 不在播放状态，忽略
    if (!this.state.isPlaying) return;

    // ✅ 鼠标滚动但不在幻灯片区域内，忽略
    const container = this.slideshowContainerRef.current;
    if (container && !container.contains(e.target)) return;

    const swiper = this.swiperRef.current?.swiper;
    if (!swiper) return;

    // ✅ 根据 deltaY 控制方向
    if (e.deltaY > 0) {
      swiper.slideNext();
    } else if (e.deltaY < 0) {
      swiper.slidePrev();
    }

    // 阻止默认滚动行为
    e.preventDefault();

    // 节流：100ms 内不处理新的滚轮事件
    this.wheelTimeout = setTimeout(() => {
      this.wheelTimeout = null;
    }, 100);
  };

  // 回话详情 
  getChatDetail = async (chatId) => {
      var rs = await conversation({ conversation_id: chatId });
      if (rs.data?.code == 200) {
        var data = rs.data.data;
        if(!data) return 

        var list = [] 

         data.dialog_segment_list.forEach((item,i)=>{
          if (item.payload.json_type == 'ppt') {
            list.push({
              code: item.content,
              thinking: '',
              type: '1',
              width:1280,
              height:720,
            })
          }
        })
        this.setState({slides:list})
      }
    };

  render() {
    const { slides, isPlaying, containerWidth, title, } = this.state;

    return (
      <motion.div
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 1 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >
        <div className={styles.pageCont}>
          <Head>
            <title>幻灯片查看器</title>
          </Head>

          <div className={styles.header}>
            <div className={styles.left}>
              <h1 className={styles.title}>{title}</h1>
              <div className={styles.description}>
                {slides.length} pages total
              </div>
            </div>
            <div className={styles.controls}>
              <button
                className={classNames(styles.playButton)}
                onClick={this.startSlideshow}
              >
                <Play size={16} />
                <span>{'播放'}</span>
              </button>
              {/* <button
                className={styles.downloadButton}
                onClick={this.handleDownload}
              >
                <Download size={16} />
                <span>下载</span>
              </button> */}
            </div>
          </div>

          {/* Waterfall layout of slides */}
          <div className={styles.slidesWaterfall}>
            <div ref={this.containerRef} style={{ width: '100%' }}></div>
            {containerWidth && (
              <>
                {slides.map((item, i) => (
                  <div>
                    <div className={styles.num}>
                      {i + 1} / {slides.length}
                    </div>
                    <div key={item.id} className={styles.waterfallItem}>
                      <Fragment
                        index={i}
                        data={item}
                        containerWidth={containerWidth}
                      />
                    </div>
                  </div>
                ))}
              </>
            )}
          </div>

          {isPlaying && (
            <div
              ref={this.slideshowContainerRef}
              style={{
                position: 'fixed',
                top: 0,
                left: 0,
                height: '100vh',
                width: '100vw',
                overflow: 'hidden',
                backgroundColor: '#000',
                zIndex: 9999,
              }}
            >
              <Swiper
                ref={this.swiperRef}
                modules={[Navigation]}
                spaceBetween={0}
                slidesPerView={1}
                navigation={false}
                loop={false}
                style={{ height: '100%' }}
                onSlideChange={(swiper) =>
                  this.setState({ activeSlideIndex: swiper.activeIndex })
                }
              >
                {slides.map((item, i) => (
                  <SwiperSlide style={{ height: '100%', width: '100%' }}>
                    {/* 拦截层：只在 isPlaying 模式下，且当前 slide 激活时加 */}
                    {this.state.showFragment &&
                      i === this.state.activeSlideIndex && (
                        <div
                          onWheel={this.handleWheel}
                          style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            zIndex: 10,
                            background: 'transparent',
                          }}
                        />
                      )}
                    <div className="slide-content">
                      {this.state.showFragment &&
                        i === this.state.activeSlideIndex && (
                          <Fragment
                            index={i}
                            data={item}
                            containerWidth={(() => {
                              return window.innerWidth;
                            })()}
                            containerHeight={(() => {
                              return window.innerHeight;
                            })()}
                            isFullscreen={true}
                          />
                        )}
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>
            </div>
          )}
        </div>
      </motion.div>
    );
  }
}

export default Comp;
